﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tunnel.Entity;
using Tunnel.Tools;

namespace Tunnel.Plan
{
    public partial class PlanForm : Form
    {
        DataTable dtPlanList;
        DataTable dtPlanInfoList;
        string planListID;
        public PlanForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 读取预案
        /// </summary>
        public async void LoadThePlanList()
        {
            string sqlLoadPlan = "SELECT M_Plan.* FROM M_Plan";
            DBHelper sdh = new DBHelper();
            dtPlanList = await sdh.GetTableAsync(sqlLoadPlan);
            cbPlanList.ValueMember = "PlanID";
            cbPlanList.DisplayMember = "PlanName";
            cbPlanList.DataSource = dtPlanList;
        }
        /// <summary>
        /// 按照预案ID读取该预案的具体内容
        /// </summary>
        public async void LoadThePlanInfoListAsync()
        {
            string sqlLoadInfoList = "SELECT M_PlanInfo.DeviceID, M_Device.Name, M_PlanInfo.PlanInfo, M_Device.TypeID,M_PlanInfo.PlanPlayList FROM M_PlanInfo LEFT OUTER JOIN M_Device ON M_Device.DeviceID LIKE '%' + M_PlanInfo.DeviceID + '%' WHERE PlanID='" + planListID + "' GROUP BY M_PlanInfo.DeviceID, M_Device.Name, M_Device.TypeID, M_PlanInfo.PlanInfo, M_PlanInfo.Number,M_PlanInfo.PlanPlayList ORDER BY M_PlanInfo.Number";
            DBHelper sdh = new DBHelper();
            dtPlanInfoList = await sdh.GetTableAsync(sqlLoadInfoList);

            dataGridView1.Rows.Clear();
            foreach (DataRow dr in dtPlanInfoList.Rows)
            {
                dataGridView1.Rows.Add(1);
                DataGridViewRow lastDr = dataGridView1.Rows[dataGridView1.RowCount - 1];
                lastDr.Cells["设备名称"].Value = dr["Name"].ToString();
                lastDr.Cells["设备状态"].Value = dr["PlanInfo"].ToString();
                lastDr.Cells["设备ID"].Value = dr["DeviceID"].ToString();
                lastDr.Cells["设备类型ID"].Value = dr["TypeID"].ToString();
                lastDr.Cells["播放列表ID"].Value = dr["PlanPlayList"].ToString();

            }
        }

        private void PlanForm_Load(object sender, EventArgs e)
        {
            LoadThePlanList();
            lbPlanProgress.Parent = pgPlanRun;
            putLabelPlanInCenter();
            lbPlanProgress.BackColor = System.Drawing.Color.Transparent;
        }
        /// <summary>
        /// 将显示进度的文字放在进度条的中心位置
        /// </summary>
        private void putLabelPlanInCenter()
        {
            lbPlanProgress.Location = new Point((pgPlanRun.Size.Width - lbPlanProgress.Size.Width) / 2, (pgPlanRun.Size.Height - lbPlanProgress.Size.Height) / 2);
        }

        private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString("第" + (e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture) + "条", new Font("等线", 12, FontStyle.Regular), b, e.RowBounds.Location.X + 17, e.RowBounds.Location.Y + 3);
            }
        }

        private void RowUp_Click(object sender, EventArgs e)
        {
            int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == 0)
            {
                MessageBox.Show("已经是第一行了!");
                return;
            }

            List<string> list = new List<string>();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (dataGridView1.SelectedRows[0].Cells[i].Value != null)
                {
                    list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把当前选中行的数据存入list数组中    
                }
                else
                {
                    list.Add("");
                }
            }
            dataGridView1.Rows[rowIndex].Selected = false;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex - 1].Cells[j].Value;
                dataGridView1.Rows[rowIndex - 1].Cells[j].Value = list[j].ToString();
            }
            dataGridView1.Rows[rowIndex - 1].Selected = true;
        }

        private void RowDown_Click(object sender, EventArgs e)
        {
            int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == dataGridView1.Rows.Count - 1)
            {
                MessageBox.Show("已经是最后一行了!");
                return;
            }

            List<string> list = new List<string>();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (dataGridView1.SelectedRows[0].Cells[i].Value != null)
                {
                    list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把当前选中行的数据存入list数组中    
                }
                else
                {
                    list.Add("");
                }
            }
            dataGridView1.Rows[rowIndex].Selected = false;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex + 1].Cells[j].Value;
                dataGridView1.Rows[rowIndex + 1].Cells[j].Value = list[j].ToString();
            }
            dataGridView1.Rows[rowIndex + 1].Selected = true;
        }

        private void RowDelete_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
        }

        private void RowInsert_Click(object sender, EventArgs e)
        {
            PlanInfoAdd f = new PlanInfoAdd(this);
            f.StartPosition = FormStartPosition.CenterScreen;
            f.ShowDialog();
        }

        private void AddPlan_Click(object sender, EventArgs e)
        {
            PlanAdd f = new PlanAdd(this);
            f.StartPosition = FormStartPosition.CenterScreen;
            f.Show();
        }

        private async void DeletePlan_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除这个预案及其全部内容吗？", "请确认", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                string sqlDeletePlayList = "DELETE FROM M_Plan WHERE PlanID='" + cbPlanList.SelectedValue.ToString() + "'";
                string sqlDeletePlayListInfo = "DELETE FROM M_PlanInfo WHERE PlanID='" + cbPlanList.SelectedValue.ToString() + "'";
                string[] sqlDeleteList = { sqlDeletePlayList, sqlDeletePlayListInfo };
                DBHelper sdh = new DBHelper();
                int count = await sdh.RunTransactionCommandsAsync(sqlDeleteList);
                if (count != 0)
                {
                    MessageBox.Show("删除成功！");
                }
                LoadThePlanList();

            }
        }

        private async void ListSave_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定要保存这个预案么？", "预案保存确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                int number = 1;
                List<string> lslist = new List<string>();
                string sqlClear = "delete from M_PlanInfo WHERE PlanID='" + planListID + "'";
                lslist.Add(sqlClear);
                //添加预案内容的SQL语句
                foreach (DataGridViewRow dgvr in dataGridView1.Rows)
                {
                    string playlistid;
                    if (dgvr.Cells["播放列表ID"].Value != null)
                    {
                        playlistid = dgvr.Cells["播放列表ID"].Value.ToString();
                    }
                    else
                    {
                        playlistid = "";
                    }
                    string sqlInfoInsert = "INSERT INTO M_PlanInfo(PlanInfoID,PlanID,DeviceID,PlanInfo,PlanPlayList,Number) VALUES ('" + DBHelper.GetGuid + "','" + planListID + "','" + dgvr.Cells["设备ID"].Value.ToString() + "','" + dgvr.Cells["设备状态"].Value.ToString() + "','" + playlistid + "','" + number + "')";
                    number++;
                    lslist.Add(sqlInfoInsert);
                }
                //修改预案描述的SQL语句
                string sqlUpdatePlanText = "UPDATE M_Plan SET PlanText='" + planText.Text + "' WHERE PlanID='" + planListID + "'";
                lslist.Add(sqlUpdatePlanText);

                DBHelper sdh = new DBHelper();
                int i = await sdh.RunTransactionCommandsAsync(lslist);
                if (i != 0)
                {
                    MessageBox.Show("已保存该预案，共" + (number - 1).ToString() + "条", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void CbPlanList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbPlanList.SelectedValue != null && dtPlanList.Rows.Count != 0)
            {
                planListID = cbPlanList.SelectedValue.ToString();
                LoadThePlanInfoListAsync();
                var dr = from s1 in dtPlanList.AsEnumerable()
                         where s1.Field<string>("PlanID") == planListID
                         select s1;
                DataRow s = dr.ToList()[0];
                string _planText = s["PlanText"].ToString();
                planText.Text = _planText;
            }
        }

        private void PublishList_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定要运行这个预案么？", "预案运行确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr != DialogResult.Yes)
                return;
            List<(string, string, string, string, string)> planInfoElements = new List<(string, string, string, string, string)>();
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                //PlanInfoElement planInfoElement = new PlanInfoElement();
                string deviceName = dgvr.Cells["设备名称"].Value.ToString();
                string deviceStatus = dgvr.Cells["设备状态"].Value.ToString();
                string deviceID = dgvr.Cells["设备ID"].Value.ToString();
                string deviceTypeID = dgvr.Cells["设备类型ID"].Value.ToString();
                string devicePlayListID = string.Empty;
                if (dgvr.Cells["播放列表ID"].Value != null)
                {
                    devicePlayListID = dgvr.Cells["播放列表ID"].Value.ToString();
                }
                if (deviceID.Contains("Light"))
                {
                    deviceTypeID = "Light";
                }//在RunPlanAsync中，对于照明的类型全部用Light表示，这里的程序代表着如果DeviceID包含有Light，则将其类型更改为Light
                planInfoElements.Add((deviceName, deviceStatus, deviceID, deviceTypeID, devicePlayListID));
            }
            bwRunPlan.RunWorkerAsync(planInfoElements);
        }

        private void BwRunPlan_DoWork(object sender, DoWorkEventArgs e)
        {
            var planInfoElements = e.Argument as List<(string, string, string, string, string)>;
            BackgroundWorker bwRunPlan = sender as BackgroundWorker;
            DataDeal.RunPlan(planInfoElements, bwRunPlan);
        }

        private void BwRunPlan_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int progress = e.ProgressPercentage;
            string progressText = e.UserState as string;
            if (progress > 0)
            {
                publishList.Enabled = false;
            }
            pgPlanRun.Value = progress;
            lbPlanProgress.Text = progressText;
            putLabelPlanInCenter();
        }

        private void BwRunPlan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            publishList.Enabled = true;
            DataDeal.LogDB("", "", "执行预案[" + cbPlanList.Text + "]");
            MessageBox.Show("预案指令已下发完成");
        }
    }
}
